<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class ArticleCategory extends Model
{
    use SoftDeletes;
    protected $table = 'article_categories';

    /**
     * 定义主键
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 禁止批量赋值的字段
     *
     * @var array
     */
    protected $guarded = ['id','created_at','deleted_at'];

    /**
     * 软删除应该被调整为日期的属性
     * [$dates description]
     * @var [type]
     */
    protected $dates=[
        'created_at', 'updated_at','deleted_at'
    ];

    protected $appends = ['category_img_url'];


    public function getCategoryImgUrlAttribute()
    {
        return config('app.img_url') . $this -> category_img;
    }


    // 通过父类获取子类的Id
    public static function getChildCid($pid){

        return self::where('parent_id',$pid) -> pluck('id');
    }

    // 监测文章某块是否 需要 定位
    public static function region_check($category_id){

        $cate = self::find($category_id);
        $res = $cate ? $cate -> is_region : 0;

        return $res ? true : false;
    }

    /**
     * 获得该分类下的全部子分类
     * @param int $parentId
     * @return int[]
     */
    public static function getChild($parentId = 0)
    {
        if ($parentId == 0) {
            return [0];
        }
        $resId[] = $parentId;
        // 获得下一级分类
        $childCategory = ArticleCategory::where('parent_id', $parentId)->get(['id']);
        foreach ($childCategory as $childCategoryVal) {
            $resId[] = $childCategoryVal->id;

            // 获得下下一级分类
            $sChildCategorry = ArticleCategory::where('parent_id', $childCategoryVal->id)->get(['id']);
            if ($sChildCategorry) {
                foreach ($sChildCategorry as $sChildCategorryVal) {
                    $resId[] = $sChildCategorryVal->id;
                }
            }
        }

        return $resId;
    }
}
